import { View, Text, ScrollView, DeviceEventEmitter } from 'react-native';
import FontAwesome from '@expo/vector-icons/FontAwesome';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import MaterialCommunityIcons from '@expo/vector-icons/MaterialCommunityIcons';
import { RootView, Header } from '../../components/Layout';
import ProductServer from '../../common/service/ProductServer';
import CommonServer from '../../common/service/CommonServer';
import * as FORM from "../../components/Form"
import { CFlex, CColor } from '../../constant/css'
import { useSetState, useCurrent } from '../../common/hooks/index'
import util from '../../common/utils/util';
import { useEffect } from 'react';

// * 添加/编辑商品
export default function AddOrEdit() {
    const routerParams = util.ExpoRouter.useLocalSearchParams()
    console.log('AddOrEdit :>> ', JSON.stringify(routerParams))

    const [state, setState] = useSetState({
        form: {
            image: [],
            cover: '',
            hash: '',
            pId: "",
            enterDate: new Date(),
            name: "",
            pIp: "",
            category: "",
            categoryDesc: "",
            source: "",
            sourceDesc: "",
            status: "",
            statusDesc: '',
            boxPrice: 0,
            buyPrice: 0,
            sellPrice: 0,
            guidePrice: 0,
            breakPrice: 0,
            stock: 0,
            postage: 0,
        },

        category: [],
        source: [],
        ip: [],
        status: [],
        isLoading: false,
    })

    useEffect(() => {
        loadCategory()
        if (routerParams.id) { // 编辑
            loadDetail()
        }
    }, [])

    useEffect(() => {
        const { boxPrice, stock } = state.form
        let val = ''
        if (boxPrice && stock) {
            val = (boxPrice / stock).toFixed(2)
        }
        setForm({ buyPrice: val })
    }, [state.form.boxPrice, state.form.stock])

    const setForm = (obj = {}) => {
        const { form } = state
        const _ = { ...form, ...obj }
        setState({ form: _ })
    }

    const loadDetail = async () => {
        const [err, res] = await ProductServer.getProductById({ pId: routerParams.id })
        if (err) {
            util.ExpoRouter.router.back()
            return util.showError(err)
        }
        const data = res?.data || {}
        data.cover = {
            url: data.cover,
            hash: data.hash,
            canDelete: true,
        }
        data.stock = `${data.stock}`
        setState({ form: data })
    }

    const loadCategory = async () => {
        const [err, res] = await ProductServer.loadProductCategory()
        if (err) return util.showInfo(err)
        const {
            category = [],
            source = [],
            ip = [],
            status = [],
        } = res.data || []

        setState({
            category,
            source,
            ip,
            status,
        })
    }

    const uploadImage = async (res) => {
        const { url, hash } = res || {}
        setForm({
            cover: { url, hash, canDelete: true }
        })
    }

    const deleteImage = () => {
        setForm({
            cover: ''
        })
    }
    const validForm = (obj) => {
        const validConfig = {
            name: (val) => val ? '' : '请填写名称~',
            pIp: (val) => val ? '' : '请选择IP~',
            statusDesc: (val) => val ? '' : '请选择状态~',
            enterDate: (val) => val ? '' : '请填选择入库时间~',
            categoryDesc: (val) => val ? '' : '请选择分类~',
            sourceDesc: (val) => val ? '' : '请选择货源~',
            boxPrice: (val) => val ? '' : '请输入整合价~',
            stock: (val) => val ? '' : '请输入库存~',
            // buyPrice: (val) => val ? '' : '请输入进价~',
        }
        for (const key in validConfig) {
            result = validConfig[key](obj[key])
            if (result) {
                util.showInfo(result)
                return true
            }
        }
        return
    }

    const submitForm = async () => {
        const { isLoading } = state
        if (isLoading) return
        setState({ isLoading: true })
        const {
            cover,
            enterDate,
            name,
            pIp,
            category,
            source,
            status,
            boxPrice,
            buyPrice,
            sellPrice,
            stock,
            postage,
        } = state.form

        const params = {
            cover: cover.url || '',
            hash: cover.hash || '',
            enterDate,
            name,
            pIp,
            category,
            source,
            status,
            boxPrice,
            buyPrice,
            sellPrice,
            stock,
            postage,
        }
        if (validForm(state.form)) {
            return setState({ isLoading: false })
        }
        let fun = ProductServer.addProduct.bind(null, params)
        if (routerParams.id) {
            let _ = state.form
            const temp = _.cover
            _.cover = temp.url
            _.hash = temp.hash
            fun = ProductServer.updateProduct.bind(null, _.pId, _)
        }
        const [err, res] = await fun()
        if (err) {
            setState({ isLoading: false })
            return util.showInfo(err)
        }
        util.showSuccess('提交成功~')
        util.ExpoRouter.router.back()
        DeviceEventEmitter.emit('refreshProduct')
    }

    const renderHeader = () =>
        <Header
            title='添加商品'
        />

    const renderForm = () => {
        const {
            category = [],
            source = [],
            ip = [],
            status = [],
        } = state
        const data = [
            {
                key: 'name',
                type: FORM.FORM_TYPE.INPUT,
                title: '名称',
                required: true,
                textAlign: 'right',
                onClick: (val) => setForm({ name: val })
            },
            {
                key: 'pIp',
                type: FORM.FORM_TYPE.SINGLE,
                title: 'IP',
                required: true,
                singleData: ip,
                singleKey: 'key',
                onClick: (index, val) => setForm({ pIp: val })
            },
            {
                key: 'statusDesc',
                type: FORM.FORM_TYPE.SINGLE,
                title: '状态',
                required: true,
                singleData: status,
                singleKey: 'key',
                onClick: (index, val, item, source) => setForm({ status: item.value, statusDesc: item.key })
            },
            {
                key: 'enterDate',
                type: FORM.FORM_TYPE.DATE,
                title: '进货时间',
                required: true,
                onClick: (val) => setForm({ enterDate: val })
            },
            {
                key: 'categoryDesc',
                type: FORM.FORM_TYPE.SINGLE,
                title: '分类',
                required: true,
                singleData: category,
                singleKey: 'key',
                onClick: (index, val, item, source) => setForm({ category: item.value, categoryDesc: item.key })
            },
            {
                key: 'sourceDesc',
                type: FORM.FORM_TYPE.SINGLE,
                title: '货源',
                required: true,
                singleData: source,
                singleKey: 'key',
                onClick: (index, val, item, source) => setForm({ source: item.value, sourceDesc: item.key })
            },
            {
                key: 'boxPrice',
                type: FORM.FORM_TYPE.INPUT,
                title: '整盒价',
                required: true,
                textAlign: 'right',
                unit: () => <FontAwesome name="rmb" size={15} color={CColor.Red} />,
                keyboardType: 'numeric',
                onClick: (val) => setForm({ boxPrice: val })
            },
            {
                key: 'stock',
                type: FORM.FORM_TYPE.INPUT,
                title: '库存',
                required: true,
                textAlign: 'right',
                unit: () => <MaterialIcons name="inventory" size={15} color={CColor.Blue} />,
                keyboardType: 'number-pad',
                onClick: (val) => setForm({ stock: val })
            },
            {
                key: 'buyPrice',
                type: FORM.FORM_TYPE.INPUT,
                title: '进价',
                required: false,
                textAlign: 'right',
                unit: () => <FontAwesome name="rmb" size={15} color={CColor.Red} />,
                keyboardType: 'numeric',
                onClick: (val) => setForm({ buyPrice: val })
            },
            {
                key: 'sellPrice',
                type: FORM.FORM_TYPE.INPUT,
                title: '售价',
                required: false,
                textAlign: 'right',
                unit: () => <FontAwesome name="rmb" size={15} color={CColor.Red} />,
                keyboardType: 'numeric',
                onClick: (val) => setForm({ sellPrice: val })
            },
            // {
            //     key: 'postage',
            //     type: FORM.FORM_TYPE.INPUT,
            //     title: '邮费',
            //     required: false,
            //     textAlign: 'right',
            //     unit: () => <MaterialCommunityIcons name="postage-stamp" size={15} color={CColor.Purple} />,
            //     keyboardType: 'number-pad',
            //     onClick: (val) => setForm({ postage: val })
            // },
            {
                key: 'cover',
                type: FORM.FORM_TYPE.IMAGE,
                title: '封面图',
                required: false,
                showAdd: true,
                max: 1,
                addFun: uploadImage,
                deleteFun: deleteImage,
            },
        ]
        return (
            <FORM.FormList
                data={state.form}
                list={data}
            />
        )
    }

    return (
        <RootView bg={CColor.White}>
            {renderHeader()}
            <ScrollView showsVerticalScrollIndicator={false}>
                {renderForm()}
                <FORM.Button isLoading={state.isLoading} label={'确 认'} onClick={submitForm} />
                <View style={{ height: 50 }} />
            </ScrollView>
        </RootView>
    );
}
